{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                \n",
    "                for n in range(num_layers):\n",
    "                    (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                        cell_fw = cells(size_layer // 2),\n",
    "                        cell_bw = cells(size_layer // 2),\n",
    "                        inputs = encoder_embedded,\n",
    "                        sequence_length = X_seq_len,\n",
    "                        dtype = tf.float32,\n",
    "                        scope = 'bidirectional_rnn_%d'%(n))\n",
    "                    encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "                \n",
    "                bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "                last_state = tuple([bi_state] * num_layers)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = last_state,\n",
    "                                               dtype = tf.float32)\n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-8-fc126b568546>:11: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-fc126b568546>:36: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:456: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:460: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-8-fc126b568546>:43: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-fc126b568546>:48: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1,  2324, 18549,  2575, 18223, 16621, 25074,  5758, 16105,\n",
       "           9643, 14533,  2418, 17963,  9586, 20965, 16069, 31732,  8349,\n",
       "          21344,  2124, 22121, 31430, 28780,  6104, 29465, 28991, 19626,\n",
       "          31276, 30543,  6748, 28268, 14529, 19673, 29387, 14052, 22645,\n",
       "          22591]],\n",
       " \n",
       "        [[    1,  4750, 23343, 23915, 14818, 27668,  1301, 23257,  8883,\n",
       "           5229,  6420,  9555, 16498, 17761, 17527, 24783, 21504, 29624,\n",
       "           5422, 10897,  1345, 29281, 12418,   391, 17635, 22516, 31582,\n",
       "          12158,  8465,  8234,  3945, 19783, 31592, 18671, 23575, 25175,\n",
       "          30270]],\n",
       " \n",
       "        [[    1, 11165, 28230, 28543,  3588,  8446, 30983,  5646, 18574,\n",
       "          11500, 15001, 18724, 12355, 27114, 26040, 21531, 20297, 18974,\n",
       "          19791,  5791, 18787,  2122, 24283, 23086, 15403, 16007,  4479,\n",
       "           2500,   998, 30034,   479, 21757, 30849, 28705, 20484, 10625,\n",
       "          10963]],\n",
       " \n",
       "        [[    1, 21566,  5275, 16424, 18786, 23284, 14270, 19038, 29192,\n",
       "          18887, 29299, 21467, 19797, 17395, 29100, 20028,  1229, 16055,\n",
       "          22997,  9385, 19514,  4418, 31845, 26042,  9266,  1335,  3478,\n",
       "           6712, 21682,  9796, 30716,   356, 19198, 18637, 29966, 10713,\n",
       "          24315]],\n",
       " \n",
       "        [[    1, 16123, 25557,  9728, 21453,  6776, 15441, 10971, 23304,\n",
       "          24959, 21721, 10360,  1855, 22637, 23298, 26272, 27013, 11847,\n",
       "          21778, 25809,  5284, 22782, 20178,  8433, 25365,  3587,  5408,\n",
       "          11522, 13084, 13902, 17884, 15812, 17167,  1198, 20439, 15428,\n",
       "           2683]],\n",
       " \n",
       "        [[    1, 21147, 29925, 26650, 22128, 25346,  8285, 19830,  3179,\n",
       "          14751, 27000, 26475, 29160, 31503,  9476,    12, 29077, 31117,\n",
       "          27793,   944, 19313,  8688, 18711, 22847, 16255, 27079, 10947,\n",
       "          25837, 10200, 15330, 16636, 31742, 15323, 10414,  7529, 12109,\n",
       "          15700]],\n",
       " \n",
       "        [[    1,  7877, 14773,  3217, 17422,  1192,  8104, 23517,  5376,\n",
       "          24541,  9258, 17910,  3494, 16991, 25395, 23339,  4406,  9769,\n",
       "          21111, 10368,  8803, 28612,  8344, 10965,  1994,  7564, 21910,\n",
       "          27063,  1434, 21804, 14596,  9499,  5702, 21906, 30476, 21280,\n",
       "          19597]],\n",
       " \n",
       "        [[    1, 10728, 24759,  8878, 23175, 23340,  1856, 25952, 16777,\n",
       "          26837, 24365,  2439, 17991,  3285,  9794, 19027,  4322,  1352,\n",
       "          23518,  3633, 16292, 27457,  8510, 26018, 27915, 12412, 27939,\n",
       "          15962, 19784, 25197, 25929,  9874, 31138, 29353, 14604, 17760,\n",
       "          11035]],\n",
       " \n",
       "        [[    1, 24274,   548, 31365,  5771, 28082, 14166, 13537,  6208,\n",
       "          30799,  1245, 10927, 20928,  1061, 18775, 31173, 28322, 22261,\n",
       "           1384,  3940, 20274,  2011,  1977,  3613, 13572, 13625,  6727,\n",
       "           5969, 19057, 29188, 31618, 29662,  5689, 10011,  7001, 11295,\n",
       "          25172]],\n",
       " \n",
       "        [[    1, 17786, 21104, 19157, 31089, 21808, 19376, 27435, 22699,\n",
       "          16683,  6913, 22721, 25268, 20002, 16191, 14436, 22575, 18775,\n",
       "           7389, 28126,  3829, 31173,  3472,  9470, 20906, 22210,  1466,\n",
       "           5234, 18870, 26948,  5114, 21135, 31491,  9718, 28972, 19195,\n",
       "          29744]]], dtype=int32), 10.369235, 0.0]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:55<00:00,  3.29it/s, accuracy=0.0875, cost=7.25]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.29it/s, accuracy=0.0806, cost=6.93]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.513433, training avg acc 0.090746\n",
      "epoch 1, testing avg loss 7.150572, testing avg acc 0.106905\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:07<00:00,  3.65it/s, accuracy=0.108, cost=6.89] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.45it/s, accuracy=0.134, cost=6.7]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 6.957252, training avg acc 0.113566\n",
      "epoch 2, testing avg loss 6.863763, testing avg acc 0.117497\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.65it/s, accuracy=0.107, cost=6.65] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.43it/s, accuracy=0.102, cost=6.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 6.734281, training avg acc 0.117395\n",
      "epoch 3, testing avg loss 6.758579, testing avg acc 0.118733\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.65it/s, accuracy=0.115, cost=6.31]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.58it/s, accuracy=0.134, cost=6.54]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 6.505643, training avg acc 0.122456\n",
      "epoch 4, testing avg loss 6.641923, testing avg acc 0.122730\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:07<00:00,  3.65it/s, accuracy=0.119, cost=6.05]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.54it/s, accuracy=0.129, cost=6.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 6.293120, training avg acc 0.126598\n",
      "epoch 5, testing avg loss 6.578824, testing avg acc 0.123877\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.65it/s, accuracy=0.121, cost=5.88]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.46it/s, accuracy=0.118, cost=6.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 6.146331, training avg acc 0.129386\n",
      "epoch 6, testing avg loss 6.564600, testing avg acc 0.124301\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.64it/s, accuracy=0.132, cost=5.7] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.49it/s, accuracy=0.124, cost=6.53]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 6.047075, training avg acc 0.131729\n",
      "epoch 7, testing avg loss 6.558663, testing avg acc 0.125543\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.65it/s, accuracy=0.134, cost=5.58]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.47it/s, accuracy=0.118, cost=6.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 5.966578, training avg acc 0.134068\n",
      "epoch 8, testing avg loss 6.567407, testing avg acc 0.124931\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:07<00:00,  3.66it/s, accuracy=0.147, cost=5.43]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.56it/s, accuracy=0.108, cost=6.56]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 5.896275, training avg acc 0.136329\n",
      "epoch 9, testing avg loss 6.578993, testing avg acc 0.125389\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:29<00:00,  3.48it/s, accuracy=0.145, cost=5.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.63it/s, accuracy=0.108, cost=6.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 5.834312, training avg acc 0.138534\n",
      "epoch 10, testing avg loss 6.594963, testing avg acc 0.124832\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:06<00:00,  3.66it/s, accuracy=0.157, cost=5.26]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.50it/s, accuracy=0.113, cost=6.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 5.782951, training avg acc 0.140459\n",
      "epoch 11, testing avg loss 6.612617, testing avg acc 0.125408\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:02<00:00,  3.70it/s, accuracy=0.161, cost=5.18]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.58it/s, accuracy=0.108, cost=6.5] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 5.739080, training avg acc 0.142177\n",
      "epoch 12, testing avg loss 6.632434, testing avg acc 0.125032\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:04<00:00,  3.68it/s, accuracy=0.17, cost=5.13] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.38it/s, accuracy=0.118, cost=6.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 5.697386, training avg acc 0.144083\n",
      "epoch 13, testing avg loss 6.651330, testing avg acc 0.125281\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:09<00:00,  3.64it/s, accuracy=0.172, cost=5.05]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.42it/s, accuracy=0.113, cost=6.55]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 5.658857, training avg acc 0.145750\n",
      "epoch 14, testing avg loss 6.671959, testing avg acc 0.124933\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:09<00:00,  3.64it/s, accuracy=0.174, cost=4.98]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.49it/s, accuracy=0.118, cost=6.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 5.626297, training avg acc 0.147338\n",
      "epoch 15, testing avg loss 6.692204, testing avg acc 0.125278\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:09<00:00,  3.64it/s, accuracy=0.179, cost=4.98]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.37it/s, accuracy=0.102, cost=6.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 5.595733, training avg acc 0.148941\n",
      "epoch 16, testing avg loss 6.712507, testing avg acc 0.123798\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:09<00:00,  3.64it/s, accuracy=0.187, cost=4.89]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.41it/s, accuracy=0.113, cost=6.64]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 5.569538, training avg acc 0.150181\n",
      "epoch 17, testing avg loss 6.737535, testing avg acc 0.124143\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:09<00:00,  3.64it/s, accuracy=0.191, cost=4.86]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.47it/s, accuracy=0.108, cost=6.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 5.549563, training avg acc 0.151302\n",
      "epoch 18, testing avg loss 6.747468, testing avg acc 0.123560\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:07<00:00,  3.65it/s, accuracy=0.2, cost=4.83]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.48it/s, accuracy=0.108, cost=6.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 5.526848, training avg acc 0.152486\n",
      "epoch 19, testing avg loss 6.766128, testing avg acc 0.123466\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.65it/s, accuracy=0.193, cost=4.81]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.62it/s, accuracy=0.113, cost=6.66]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 5.506379, training avg acc 0.153467\n",
      "epoch 20, testing avg loss 6.789813, testing avg acc 0.122652\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [01:35<00:00,  2.39s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6.319555e-05"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
